import { writable, readable, get, derived } from 'svelte/store'

// 1
const count = writable(0)

function getCount () {
  return get(count)
}



// 2
const count2 = writable(0, () => {
  console.log('got a subscriber')
  return () => console.log('no more subscribers')
})
const unsubscribe = count2.subscribe((v) => {
  console.log("count2: ", v)
})


// 3 
const time = readable(new Date(), (set) => {
  set(new Date())

  const interval = setInterval(() => {
    set(new Date())
  }, 1e3)

  return () => clearInterval(interval)
})



/**
 * 创建用户资料仓库
 */
function createUserInfo () {
  const { subscribe, set, update } = writable(null)

  /**
   * 赋值用户资料
   * @param {Object} obj 对象
   */
  function setInfo (obj) {
    obj && set(obj)
  }

  /**
   * 更新用户资料
   * @param {string} key 更新的字段名
   * @param {any} value 更新的值
   */
  function updateInfo (key, value) {
    update((info) => {
      info && info.hasOwnProperty([key]) && value && (info[key] = value)
      return info
    })
  }
  return { subscribe, setInfo, updateInfo }
}
const userInfo = createUserInfo()




export { count, getCount, count2, unsubscribe, time, userInfo }